<!--
 * @Author: Bennty
 * @Date: 2024-08-07 14:00:12
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2024-10-31 10:56:16
 * @Description: 请填写简介
-->
<template>
    <div class="p-2">
        <transition 
        :enter-active-class="proxy?.animate.searchAnimate.enter"
        :leave-active-class="proxy?.animate.searchAnimate.leave">
            <div class="search">
                <el-form :model="queryParams" :inline="true" ref="queryFormRef">
                    <el-form-item label="产品大类" prop="productCategoriesType">
                        <el-select v-model="queryParams.productCategoriesType" placeholder="请选择">
                            <el-option v-for="item in total_catagory" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品小类" prop="productSubcategoryType">
                        <el-select v-model="queryParams.productSubcategoryType" placeholder="请选择">
                            <el-option v-for="item in single_catagory" :key="item.value" :label="item.label" :value="item.value" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="模糊搜索" prop="productName">
                        <el-input v-model="queryParams.productName" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </transition>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="8" class="mb8">
                    <el-col class="header-button-container" :span="1.5">
                        <el-button type="primary" plain icon="Download" @click="onClickExport" >导出</el-button>
                    </el-col>
                    <el-col :span="1.5" :offset="1">
                        <span class="price-tip">库存金额：￥{{ inventoryAmount }}</span>
                    </el-col>
                    <el-col :span="1.5" :offset="1">
                        <span class="price-tip">库存金额(成本)：￥{{ inventoryCostAmount }}</span>
                    </el-col>
                </el-row>
            </template>
            <el-table ref="multipleTableRef" :data="productList" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column label="产品大类" prop="productCategoriesName"></el-table-column>
                <el-table-column label="产品小类" prop="productSubcategoryName"></el-table-column>
                <el-table-column label="产品名称" prop="productName"></el-table-column>
                <el-table-column label="当前库存箱数" prop="inventoryBoxNumber"></el-table-column>
                <el-table-column label="库存数量(只)" prop="inventoryNumber"></el-table-column>
                <el-table-column label="单价">
                    <template #default="scope">
                        <span> {{ `￥${scope.row.productPrice}` }} </span>
                    </template>
                </el-table-column>
                <el-table-column label="库存金额">
                    <template #default="scope">
                        <span> {{ `￥${scope.row.inventoryMoney}` }} </span>
                    </template>
                </el-table-column>
                <el-table-column label="最低库存">
                    <template #default="scope">
                        <span :class="`min-inventory ${scope.row.isAlert?'alert':'not-alert'}`"> {{ scope.row.lowInventory }} </span>
                    </template>
                </el-table-column>
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-tooltip content="详情" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#69AFF0'}"  icon="Memo" @click="handleClickCheckDetails(scope.row)" ></el-button>
                        </el-tooltip>
                        <el-tooltip content="入库" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#FBBBBA'}"  icon="Back" @click="handleClickInStorage(scope.row)"></el-button>
                        </el-tooltip>
                        <el-tooltip content="出库" placement="top">
                            <el-button link :style="{fontSize:'15px',color:'#B886F8'}"  icon="Right" @click="handleClickOutStorage(scope.row)" ></el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="totalData > 0" :total="totalData" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
                @pagination="getProductList" />
        </el-card>
        <el-dialog v-model="inStorageVisible" title="入库" width="25%" @close="handleCloseInStorage">
            <el-form :model="inStorageFormData" ref="inStorageFormRef">
                <el-form-item label="产品名称">
                    <span>{{ productInfo?.productName }}</span>
                </el-form-item>
                <el-form-item label="箱数" prop="boxNumber">
                    <el-input type="number" v-model.number="inStorageFormData.boxNumber" disabled placeholder="请输入" />
                </el-form-item>
                <el-form-item label="数量" prop="number">
                    <el-input type="number" v-model.number="inStorageFormData.number" @change="throttledOnInstorage" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="inStorageFormData.remark" type="textarea" placeholder="请输入" maxlength="125" show-word-limit></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitInStorage" >确 定</el-button>
                    <el-button @click="handleCloseInStorage">取 消</el-button>
                </div>
            </template>
        </el-dialog>
        <el-dialog v-model="outStorageVisible" title="出库" width="25%" @close="handleCloseOutStorage">
            <el-form :model="outStorageFormData" ref="outStorageFormRef">
                <el-form-item label="产品名称">
                    <span>{{ productInfo?.productName }}</span>
                </el-form-item>
                <el-form-item label="箱数" prop="boxNumber">
                    <el-input v-model.number="outStorageFormData.boxNumber" disabled placeholder="请输入" />
                </el-form-item>
                <el-form-item label="数量" prop="number">
                    <el-input v-model.number="outStorageFormData.number" @change="throttledOnOutstorage" placeholder="请输入" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="outStorageFormData.remark" type="textarea" placeholder="请输入" maxlength="125" show-word-limit></el-input>
                </el-form-item>
                <el-form-item prop="status">
                    <el-switch
                        v-model="outStorageFormData.useStatus"
                        class="ml-2"
                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949; margin-right: 10px"
                        :active-value="1"
                        :inactive-value="2"
                    />
                    <span v-if="outStorageFormData.useStatus == 1" :style="{color:'#13ce66'}">自用</span>
                    <span v-else :style="{color:'#ff4949'}">废弃</span>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button  type="primary" @click="handleSubmitOutStorage">确 定</el-button>
                    <el-button @click="handleCloseOutStorage">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import type { FormInstance } from 'element-plus';
import { ElTable } from 'element-plus';
import { preparedProductVO } from '@/api/sj/warehouse/productInventory/types';
import { useRouter } from 'vue-router';
import { getProductListApi,getProductByIdApi,addInOutStorageApi, calculateBoxNumberApi,exportProductListApi } from '@/api/sj/warehouse/productInventory';
import { throttling } from '@/utils/optimization';
import { getFormattedTimestamp } from '@/utils/dateFormat';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { total_catagory,single_catagory } = toRefs<any>(proxy?.useDict('total_catagory','single_catagory'));
const router = useRouter();
const queryFormRef = ref<FormInstance>();
const inventoryAmount = ref<number>();
const inventoryCostAmount = ref<number>();
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<preparedProductVO[]>([]);
const productList = ref<preparedProductVO[]>([]);
const totalData = ref(0);
const productInfo = ref<any>();
const inStorageVisible = ref(false);
const inStorageProduct = ref<preparedProductVO>({});
const inStorageFormRef = ref<FormInstance>();
const outStorageVisible = ref(false);
const outStorageFormRef = ref<FormInstance>();
const data = reactive({
    queryParams:{
        productCategoriesType: undefined,
        productSubcategoryType: undefined,
        productName: undefined,
        pageNum: 1,
        pageSize: 30
    },
    inStorageFormData:{
        boxNumber: undefined,
        number: undefined,
        remark: undefined,
        inOutType: 1,
        useStatus: 1
    },
    outStorageFormData:{
        boxNumber: undefined,
        number: undefined,
        status: true,
        remark: undefined,
        inOutType: 2,
        useStatus: 1
    }
});

const { queryParams,inStorageFormData, outStorageFormData } = toRefs(data);

/** 获取成品列表 */
const getProductList = async () => {
    const result = await getProductListApi(queryParams.value);
    productList.value = result.data.dataPage.records;
    totalData.value = result.data.dataPage.total;
    inventoryAmount.value = result.data.inventoryAmount;
    inventoryCostAmount.value = result.data.inventoryCostAmount;
};

/** 搜索按钮操作 */
const handleQuery = () => {
    queryParams.value.pageNum = 1;
    getProductList();
};

const resetQuery = () => {
    queryFormRef.value?.resetFields();
    handleQuery();
};

const handleSelectionChange = (val: preparedProductVO[]) => {
    multipleSelection.value = val
};

/** 点击导出 */
const onClickExport = async () => {
    proxy?.download('/system/productInfo/export',{...queryParams.value},`成品库存列表${getFormattedTimestamp()}.xlsx`);
};

/** 计算箱数 */
const calculateBoxNumber = async(boxNumber: any) => {
    const submitData = {
        bomId: productInfo.value.bomId,
        boxNumber: boxNumber
    };
    const result = await calculateBoxNumberApi(submitData);
    return result;
};

/** 点击入库 */
const handleClickInStorage = async (row:preparedProductVO)=>{
    const {code, data} = await getProductByIdApi(row.id);
    if(code == 200){
        productInfo.value = data;
        inStorageVisible.value = true;
    };
};

/** 计算入库箱数 */
const onInstorageNumberChange:Function = (value: any) => {
    calculateBoxNumber(value).then((result)=>{
        if(result.code == 200){
            inStorageFormData.value.boxNumber = result.data;
        };
    });
};

const throttledOnInstorage = throttling(onInstorageNumberChange, 100);

const handleCloseInStorage = ()=>{
    inStorageVisible.value = false;
    inStorageProduct.value = {};
    inStorageFormRef.value?.resetFields();
};

/** 提交入库 */
const handleSubmitInStorage = async ()=>{
    const submitData = {
        ...inStorageFormData.value,
        productId: productInfo.value.id,
        productName: productInfo.value.productName
    };
    const { code } = await addInOutStorageApi(submitData);
    if(code == 200){
        proxy?.$modal.msgSuccess('入库成功');
        handleCloseInStorage();
        getProductList();
    };
};

/** 点击出库 */
const handleClickOutStorage = async (row:preparedProductVO)=>{
    const {code, data} = await getProductByIdApi(row.id);
    if(code == 200){
        productInfo.value = data;
        outStorageVisible.value = true;
    };
};

/** 计算出库箱数 */
const onOutstorageNumberChange = (value: any) => {
    calculateBoxNumber(value).then((result)=>{
        if(result.code == 200){
            outStorageFormData.value.boxNumber = result.data;
        };
    });
};

const throttledOnOutstorage = throttling(onOutstorageNumberChange, 100);

const handleCloseOutStorage = ()=>{
    outStorageVisible.value = false;
    outStorageFormRef.value?.resetFields();
};

/** 提交入库 */
const handleSubmitOutStorage = async ()=>{
    const submitData = {
        ...outStorageFormData.value,
        productId: productInfo.value.id,
        productName: productInfo.value.productName
    };
    const {code} = await addInOutStorageApi(submitData);
    if(code == 200){
        proxy?.$modal.msgSuccess('出库成功');
        handleCloseOutStorage();
        getProductList();
    }; 
};

/**点击查看详情 */
const handleClickCheckDetails = (row: any)=>{
    router.push(`/warehouse/checkProduct/${row.bomId}`);
};

onMounted(()=>{
    getProductList();
    
});
</script>

<style lang="scss" scoped>
.price-tip{
    display: flex;
    align-items: center;
    height: 100%;
}
.alert{
    color: #F75C4E;
    line-height: 10;
}
.not-alert{
    line-height: 10;
}
.dialog-footer{
    display: flex;
    justify-content: center;
}
</style>
